package com.useeinfo.oa.open.admin.repair;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.AliJsonObjectCover;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.PositionBiz;
import com.useeinfo.oa.modules.base.biz.ResourceBiz;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.maintaining.entity.MaintainOrder;
import com.useeinfo.oa.modules.repair.biz.RepairOrderBiz;
import com.useeinfo.oa.modules.repair.biz.RepairOrderLogBiz;
import com.useeinfo.oa.modules.repair.entity.RepairOrder;
import com.useeinfo.oa.modules.repair.enums.RepairOrderLogOperationEnum;
import com.useeinfo.oa.modules.repair.enums.RepairOrderStatusEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import javafx.util.StringConverter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @Auther: xudong.sun
 * @Date: 2019/1/4 14:14
 * @Description:
 */
@Controller
@RequestMapping("/web/admin/repairOrderAudit")
public class RepairOrderAuditAction {

    @Autowired
    private RepairOrderBiz repairOrderBiz;

    @Autowired
    private SystemUserBiz systemUserBiz;

    @Autowired
    private OrganizationBiz organizationBiz;

    @Autowired
    private PositionBiz positionBiz;

    @Autowired
    private RepairOrderLogBiz repairOrderLogBiz;
    @Autowired
    private ResourceBiz resourceBiz;

    /**
     * 打开列表页面
     */
    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/repairOrderAudit/list");
        String signEnterpriseId=Configuration.getConfigurationByName("signEnterpriseId");
        modelAndView.addObject("signEnterpriseId",signEnterpriseId);
        return modelAndView;
    }


    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "searchReportCode", required = false) String searchReportCode,
                               @RequestParam(value = "orderStatus", required = false) String orderStatus,
                               @RequestParam(value = "reportContent", required = false) String reportContent,
                               @RequestParam(value = "reportType", required = false) String reportType,
                               @RequestParam(value = "reportUser", required = false) String reportUser,
                               @RequestParam(value = "orderBy", required = false) String orderBy, HttpServletRequest request){
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("reportCode", searchReportCode);
        queryParam.getSqlMap().put("repairOrderStatus", orderStatus);
        queryParam.getSqlMap().put("reportContent", reportContent);
        queryParam.getSqlMap().put("repairOrderTypeEnum", reportType);
        queryParam.getSqlMap().put("reportUser", reportUser);
        if (StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(request);
        sessionUser = systemUserBiz.findModel(sessionUser.getId());
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
            SystemUserOrganization systemUserOrganization = sessionUser.getOrganization(enterprise, sessionUser.getSystemUserOrganizationSet());
            Position position = sessionUser.getPosition(enterprise, sessionUser.getPositionSet());
            if(systemUserOrganization != null){
                queryParam.getSqlMap().put("auditOrganizationId", StringConverters.null2String(systemUserOrganization.getOrganization().getId()));
            }
            queryParam.getSqlMap().put("auditUserId",StringConverters.null2String(sessionUser.getId()));
            if(position != null){
                queryParam.getSqlMap().put("auditPositionId",StringConverters.null2String(position.getId()));
            }
        }
        queryParam.getSqlMap().put("repairOrderStatus","IN_AUDITING");
        return repairOrderBiz.findJSONList(queryParam);
    }

    /**
     * 终身评分
     * @param repairOrderId
     * @param type
     * @param request
     * @param score
     * @param remark
     * @param reason
     * @return
     */
    @RequestMapping("/audit")
    @ResponseBody
    public ResultDto audit(@RequestParam(value = "repairOrderId", required = false) String repairOrderId,
                           @RequestParam(value = "type",required = false) Boolean type, HttpServletRequest request,
                           String score,String remark,String reason
                            ){

        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderId));
        // 获取审批流
        JSONArray jsonArray = JSONArray.parseArray(repairOrder.getFlow());
        if (type) {

            //维修单中的审批流快照
            int auditLevel = repairOrder.getAuditLevel();
            if (jsonArray.size() > 0 && auditLevel + 1 < jsonArray.size()) {
                repairOrder.setAuditLevel(auditLevel + 1);
                repairOrder.setAuditUser(null);
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(auditLevel + 1);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if ("POSITION".equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(relationId));
                } else if ("USER".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(relationId));
                } else {
                    repairOrder.setAuditUser(repairOrder.getReportUser());
                }
                repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.AUDIT, sessionEnterprise, reason);

            }
            if (jsonArray.size() > 0 && jsonArray.size() < 2  && auditLevel + 1 == jsonArray.size()) {
                // 如果存在审批流，且审批流中只有一层审批。
                if(StringUtils.isNotBlank(score)){
                    repairOrder.setLastScore(StringConverters.null2Int(score));
                }
                if(StringUtils.isNotBlank(remark)){
                    repairOrder.setLastRemark(remark);
                }
                repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
                repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.AUDIT, sessionEnterprise, reason);
                repairOrderLogBiz.addLog(repairOrder, repairOrder.getReceiveUser(), RepairOrderLogOperationEnum.FINISH, sessionEnterprise, null);

            } else if (jsonArray.size() > 0 && auditLevel + 1 == jsonArray.size()) {
                if(StringUtils.isNotBlank(score)){
                    repairOrder.setLastScore(StringConverters.null2Int(score));
                }
                if(StringUtils.isNotBlank(remark)){
                    repairOrder.setLastRemark(remark);
                }
                repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
                repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.AUDIT, sessionEnterprise, reason);
                repairOrderLogBiz.addLog(repairOrder, repairOrder.getReceiveUser(), RepairOrderLogOperationEnum.FINISH, sessionEnterprise, null);

            }

        } else {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.REJECTED);
            //如果是400工单，删除签字图片，清空维修确认时间，清空签字时间
            repairOrder.setSignDate(null);
            repairOrder.setConfirmDate(null);
            repairOrder.setCheckRepair(false);
            Set<Resource> resources=repairOrder.getFinishPhoto();
            if (CollectionUtils.isNotEmpty(resources)) {
                for(Resource resource:resources){
                    if (resource.getResourceName().equals("签字图片")) {
                        resources.remove(resource);
                        resourceBiz.deleteLogic(resource);
                        break;
                    }
                }
                repairOrder.setFinishPhoto(resources);
            }

            if (jsonArray.size() > 0) {
                repairOrder.setAuditUser(null);
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditPosition(null);
                repairOrder.setAuditLevel(0);
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(StringConverters.null2Long(organizationId)));
                if ("POSITION".equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("USER".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(StringConverters.null2Long(relationId)));
                } else {
                    repairOrder.setAuditUser(repairOrder.getReportUser());
                }
            }
            repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.REJECT, sessionEnterprise, null);
        }
        return ResultUtil.success();
    }

    /**
     * 终极审核评分页面
     *
     * @param id
     * @return
     */
    @RequestMapping("/judgeOrder")
    public ModelAndView judgeOrder(String id) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("repairOrderId", id);
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("repairOrder", repairOrder);
        modelAndView.setViewName("pages/admin/repairOrderAudit/judgeRepairOrder");
        return modelAndView;
    }

    /**
     * 审核不通过页面
     *
     * @param id
     * @param
     * @return
     */
    @RequestMapping("/auditOrderEdit")
    public ModelAndView auditOrderEdit(String id) {

        ModelAndView modelAndView = new ModelAndView();
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("repairOrder", repairOrder);
        modelAndView.setViewName("pages/admin/repairOrderAudit/unPassOrder");
        return modelAndView;
    }
}
